
import { getCartList, changeCartCount, deleteCart } from '@/api/cart'

// 购物车数据
export default {

  namespaced: 'cart',
  //   数据
  state: {
    cartList: []
  },
  //   同步修改
  mutations: {
    // 本地存储数据
    changeCartList (state, list) {
      state.cartList = list
    },
    // 商品选中情况切换
    toggleCheck (state, id) {
      const goods = state.cartList.find(item => item.goods_id === id)
      console.log(goods)
      goods.isChecked = !goods.isChecked
    },
    // 全选
    toggleAllCheck (state, isChecked) {
      state.cartList.forEach(item => {
        item.isChecked = isChecked
      })
    },
    // 修改数量本地存储
    changeCount (state, { goodsId, goodsNum }) {
      const goods = state.cartList.find(item => item.goods_id === goodsId)
      goods.goods_num = goodsNum
    }
  },
  //   异步修改
  actions: {
    async getCartAction (context) {
      const res = await getCartList()
      //   console.log(res.data.list)
      //   需要手动维护数据，为数组每一项添加一个isChecked属性来描述其是否选中
      res.data.list.forEach(item => {
        item.isChecked = true
      })
      context.commit('changeCartList', res.data.list)
    },
    async changeCountAction (context, obj) {
      const { goodsNum, goodsId, goodsSkuId } = obj
      context.commit('changeCount', { goodsNum, goodsId })
      const res = await changeCartCount(goodsId, goodsNum, goodsSkuId)
      console.log(res)
    },
    async delCart (context) {
      const seledList = context.getters.selectCartList
      const cartIds = seledList.map(item => {
        return item.id
      })
      console.log(cartIds)
      const res = await deleteCart(cartIds)
      console.log(res)

      context.dispatch('getCartAction')
    }

  },
  //   计算属性
  getters: {
  // 购物车总数
    cartTotal (state) {
      return state.cartList.reduce((total, item) => total + item.goods_num, 0)
    },
    // 选中项
    selectCartList (state) {
      return state.cartList.filter(item => item.isChecked === true)
    },
    // 选中的总数
    selectCount (state, getters) {
      return getters.selectCartList.reduce((total, item) => total + item.goods_num, 0)
    },
    // 选中的总价
    selectPrice (state, getters) {
      return getters.selectCartList.reduce((total, item) => total + item.goods.line_price_max * item.goods_num, 0).toFixed(2)
    },
    // 是否全选
    isAllSelect (state, getters) {
      return state.cartList.every(item => item.isChecked === true)
    }
  }

}
